package come.iweb.user.servlet;

import come.iweb.user.model.User;
import come.iweb.user.service.UserService;
import come.iweb.user.service.UserServiceImpl;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("*.user")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getServletPath();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/login.user":
                handleLogin(request, response);
                break;
            case "/register.user":
                // 跳转到注册页面
                request.getRequestDispatcher("/register.html").forward(request, response);
                break;
            case "/check-login.user":
                handleCheckLogin(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getServletPath();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/login.user":
                handleLoginPost(request, response);
                break;
            case "/register.user":
                handleRegister(request, response);
                break;
            case "/logout.user":
                handleLogout(request, response);
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                break;
        }
    }

    private void handleLogin(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 跳转到登录页面
        request.getRequestDispatcher("/login.html").forward(request, response);
    }

    private void handleLoginPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        Map<String, Object> result = new HashMap<>();
        
        // 参数验证
        if (username == null || username.trim().isEmpty() ||
            password == null || password.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "用户名和密码不能为空");
            response.getWriter().write(JSON.toJSONString(result));
            return;
        }
        
        // 调用Service层方法验证用户
        User user = userService.login(username, password);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
            response.getWriter().write(JSON.toJSONString(result));
            return;
        }
        
        // 登录成功，创建session
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        
        result.put("success", true);
        result.put("message", "登录成功");
        
        // 根据角色设置不同的重定向页面
        switch (user.getRole()) {
            case "admin":
                result.put("redirect", "/on_line_exam_system/admin/index.html");
                break;
            case "teacher":
                result.put("redirect", "/on_line_exam_system/teacher/index.html");
                break;
            case "student":
                result.put("redirect", "/on_line_exam_system/student/index.html");
                break;
            default:
                result.put("redirect", "/on_line_exam_system/login.html");
        }
        
        response.getWriter().write(JSON.toJSONString(result));
    }

    private void handleRegister(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        
        Map<String, Object> result = new HashMap<>();
        
        // 参数验证
        if (username == null || username.trim().isEmpty() ||
            password == null || password.trim().isEmpty() ||
            email == null || email.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "所有字段都必须填写");
            response.getWriter().write(JSON.toJSONString(result));
            return;
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 注意：实际应用中应该对密码进行加密
        user.setEmail(email);
        user.setRole("student"); // 设置默认角色
        
        // 调用Service层方法注册用户
        try {
            if (userService.register(user)) {
                result.put("success", true);
                result.put("message", "注册成功");
                result.put("redirect", "/on_line_exam_system/login.html"); // 注册成功后跳转到登录页面
            } else {
                result.put("success", false);
                result.put("message", "注册失败，用户名可能已存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "注册失败：" + e.getMessage());
        }
        
        response.getWriter().write(JSON.toJSONString(result));
    }

    private void handleCheckLogin(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();
        
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        result.put("loggedIn", user != null);
        if (user != null) {
            result.put("username", user.getUsername());
            result.put("role", user.getRole());
        }
        
        response.getWriter().write(JSON.toJSONString(result));
    }

    private void handleLogout(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> result = new HashMap<>();
        
        HttpSession session = request.getSession();
        session.invalidate();
        
        result.put("success", true);
        result.put("message", "退出成功");
        
        response.getWriter().write(JSON.toJSONString(result));
    }
}
